﻿
var ProcessChat = function () {
    var that = this;
    var name = document.getElementById('name').value;
    var msgContainer = document.getElementById('message');
    var text = document.getElementById('text');
    var address = document.getElementById('address').value;

    this.ws = null;
    this.connect = function () {
        if (this.ws == null) {
            this.ws = new WebSocket(address);
            this.regEvt();
        }
    }

    this.regEvt = function () {
        this.ws.onopen = function (e) {
            $(msgContainer).append("<div style='color:red;'>Server is connectioned</div>");
            ws.send('{<' + document.getElementById('name').value + '>}');
        };
        this.ws.onmessage = function (e) {
            $(msgContainer).append("<div style='color:blue;'>" + e.data.split(':')[3] + ":" + e.data.split(':')[4] + "</div>");
        };
        this.ws.onerror = function (e) {
            $(msgContainer).append("<div style='color:green;'>" + e.data + "</div>");
        };
        this.ws.onclose = function (e) {
            $(msgContainer).append("<div style='color:green;'>Connection is closed</div>");
        };
    }

    this.quit = function () {
        if (this.ws) {
            this.ws.close();
            $(msgContainer).append("<div style='color:green;'>Connection is closed</div>");
            this.ws = null;
        }
    }

    this.send = function () {
        this.ws.send(document.getElementById('name').value + ":" + text.value);
        text.value = '';
        text.focus();
        setTimeout(function () {
            msgContainer.scrollTop = msgContainer.getBoundingClientRect().height;
        }, 100);
    }

    this.clearMsg = function () {
        msgContainer.innerHTML = "";
    }
}